package com.exam.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.exam.pojo.*;
import com.exam.service.*;
import com.exam.service.impl.QuestionServiceImpl;
import com.exam.util.PropertiesUtil;
import com.exam.util.QuestionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄星
 * 界面的显示，已经试卷提交的操作
 * */
@Controller
@RequestMapping("/Index")
public class Index {

	@Resource
	private ApplicationContext ctx;
	@Resource(name = "mv")
	private ModelAndView mv;
	@Resource(name = "subjectServiceImpl")
	private SubjectService subjectService;
	@Resource(name = "questionServiceImpl")
	private QuestionService questionService;
	@Resource(name = "scoreServiceImpl")
	private ScoreService scoreService;
	@Resource(name = "studentServiceImpl")
	private StudentService studentService;
	@Resource(name = "scheduleServiceImpl")
	private ScheduleService scheduleService;
	/**
	 * index页面
	 */
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {

		mv.setViewName( "index" );
		return mv;

	}

	/**
	 * 主界面
	 */
	@RequestMapping("/main")
	public String main(HttpServletRequest req, HttpServletResponse resp, Model model, RedirectAttributes attributes) {

		String subjectName = (subjectService.getSubjectById( Integer.parseInt( req.getParameter( "subjectId" ) ) )).getSubjectName();//获取类别名称；

		HttpSession session = req.getSession();   //用session来存  是为了其他页面也能引用

		List<Question> choiceQuestion = questionService.getChoiceQuestionBySubjectName( subjectName );          //生成选择题
		List<List<String>> choiceAnswer = questionService.getChoiceQuestionAnswerByRandom( choiceQuestion );   //令选择题答案随机出现

		List<Question> blankQuestion = questionService.getBlankQuestionBySubjectName( subjectName );   //生成填空题
		List<List<String>> topicSplit = questionService.getBlankQuestionAnswerBySplit( blankQuestion );//令填空题题目分开

		List<Question> judgeQuestion = questionService.getJudgeQuestionBySubjectName( subjectName );   //生成判断题

		session.setAttribute( "choiceQuestion", choiceQuestion );   //选择题
		session.setAttribute( "choiceAnswer", choiceAnswer );        //选择题答案
		session.setAttribute( "blankQuestion", blankQuestion );    //填空题
		session.setAttribute( "topicSplit", topicSplit );    //填空题题目
		session.setAttribute( "judgeQuestion", judgeQuestion );    //判断题
		session.setAttribute( "subjectId", Integer.parseInt( req.getParameter( "subjectId" ) ) );    //科目ID
		System.out.println(session.getAttribute( "loginFlag" ).toString());
		String retPage = "main";
		if( "1" .equals( session.getAttribute( "loginFlag" ).toString() )){
//			判断是否登陆过，1为没有，就进入考试界面，并将标志设为2；
			session.setAttribute( "loginFlag","2" );
			int studentId = (Integer) session.getAttribute( "studentId" );
			//显示信息
			model.addAttribute( "student",studentService.getStudentById( studentId ) );
			model.addAttribute( "subjectName", subjectName  );
		}else{
			//标志设为1   并重定向到科目选择界面
			session.setAttribute( "loginFlag","1" );
			retPage = "redirect:/Login/dispatcher?status=1";
		}
//		mv.addObject( "subjectName", subjectName );
//		mv.setViewName( "main" );

		return retPage;
	}

	/**
	 * 主界面中iframe显示题目
	 */
	@RequestMapping("/question")
	public ModelAndView question() {

		mv.setViewName( "question" );
		return mv;
	}

	/**
	 * 学生点击提交之后进行没填写的判断以及全填时候分数的计算
	 * @param req 表单序列化Jason
	 * @return 提示文字
	 */
	@RequestMapping("/manualFinishExam")
	@ResponseBody
	public String manualFinishExam(HttpServletRequest req) {

		int score = 0;
		HttpSession session = req.getSession();
		Boolean checkBlanks = true, checkJudges = true, showScore = true;
		String ret = "";
		//获取题目以及选择题随机答案的结果
		List<Question> choiceQuestion = (List<Question>) session.getAttribute( "choiceQuestion" );
		List<List<String>> choiceAnswer = (List<List<String>>) session.getAttribute( "choiceAnswer" );
		List<Question> blankQuestion = (List<Question>) session.getAttribute( "blankQuestion" );
		List<Question> judgeQuestion = (List<Question>) session.getAttribute( "judgeQuestion" );

//		获取科目ID以及学生ID
		int subjectId = (Integer) session.getAttribute( "subjectId" );
		int studentId = (Integer) session.getAttribute( "studentId" );

		for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "choice" ); i++) {
			//验证选择题
			String raido = req.getParameter( "answer" + i );

			if (raido == null) {
				//如果未选，就返回未选题的ID
				ret = "choice" + i;
				checkBlanks = false;
				checkJudges = false;
				showScore = false;
				break;
			} else {
				//计算分数
				score += QuestionUtils.computeChoiceScore( Integer.parseInt( raido.trim() ), choiceQuestion.get( i - 1 ), choiceAnswer.get( i - 1 ) );
			}
		}

		if (checkBlanks) {
			//如果选择题都已经选择，判断填空题
			for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "blank" ); i++) {
				String blank = (req.getParameter( "blank" + i ));
				if (blank == null || blank.trim().equals( "null" ) || blank.trim().equals( "" )) {
					//如果未填，就返回未填写题的ID
					ret = "blank" + i;
					checkJudges = false;
					showScore = false;
					break;
				} else {
					//计算分数
					score += QuestionUtils.computeBlankScore( blank, blankQuestion.get( i - 1 ) );
				}
			}
		}

		if (checkJudges) {
			//如果填空题都已经填满 ， 判断判断题
			for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "judge" ); i++) {
				String raido = req.getParameter( "judge" + i );
				//验证判断题
				if (raido == null) {
					//如果未选，就返回未选题的ID
					ret = "judge" + i;
					showScore = false;
					break;
				} else {
					//计算分数
					score += QuestionUtils.computeJudgeScore( raido.trim(), judgeQuestion.get( i - 1 ) );
				}
			}
		}

		if (showScore) {
			//如果全选就录入成绩 并返回分数
			Student student = studentService.getStudentById( studentId );
			insScore( student.getSno(), subjectId, score );
			ret = String.valueOf( score );
		}

		return ret;
	}

	/**
	 * 时间到后自动提交试卷
	 * @param req 表单序列化Jason
	 * @return 提示文字
	 */
	@RequestMapping("/autoFinishExam")
	@ResponseBody
	public String autoFinishExam(HttpServletRequest req) {

		int score = 0;
		HttpSession session = req.getSession();
		String ret = "";
		//获得每种题目 以及选择题随机的结果
		List<Question> choiceQuestion = (List<Question>) session.getAttribute( "choiceQuestion" );
		List<List<String>> choiceAnswer = (List<List<String>>) session.getAttribute( "choiceAnswer" );
		List<Question> blankQuestion = (List<Question>) session.getAttribute( "blankQuestion" );
		List<Question> judgeQuestion = (List<Question>) session.getAttribute( "judgeQuestion" );

		for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "choice" ); i++) {
			//计算选择题
			String raido = req.getParameter( "answer" + i );

			if (raido != null) {
				score += QuestionUtils.computeChoiceScore( Integer.parseInt( raido.trim() ), choiceQuestion.get( i - 1 ), choiceAnswer.get( i - 1 ) );
			}
		}

		for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "blank" ); i++) {
			//计算填空题
			String blank = (req.getParameter( "blank" + i ));
			if (blank == null || blank.trim().equals( "null" ) || blank.trim().equals( "" )) {
			} else {
				score += QuestionUtils.computeBlankScore( blank, blankQuestion.get( i - 1 ) );
			}
		}

		for (int i = 1; i <= PropertiesUtil.getQuestionNumber( "judge" ); i++) {
			String raido = req.getParameter( "judge" + i );
			//验计算判断题
			if (raido != null) {
				score += QuestionUtils.computeJudgeScore( raido.trim(), judgeQuestion.get( i - 1 ) );
			}
		}
		//获取考试的科目ID  以及  学生ID以获取学号
		int subjectId = (Integer) session.getAttribute( "subjectId" );
		int studentId = (Integer) session.getAttribute( "studentId" );
		Student student = studentService.getStudentById( studentId );
		//插入成绩并返回分数
		if (insScore(student.getSno(), subjectId, score )) {
			ret = String.valueOf( score );
		}

		return ret;
	}

	/**
	 * 统一插入成绩的代码
	 * */
	private Boolean insScore(String sno, Integer subjectId, Integer result) {
		Boolean ret = false;
		if (scoreService.insScore( sno, subjectId, result ) > 0) {
			ret = true;
		}
		return ret;
	}
}
